﻿using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;

namespace DotNetty.Extensions
{
    class TcpServerHandler : SimpleChannelInboundHandler<object>
    {
        private readonly TcpSocketServer _server;

        public TcpServerHandler(TcpSocketServer server)
        {
            _server = server;
        }

        /// <summary>
        /// 客户端连接
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelActive(IChannelHandlerContext context)
        {
            _server.ClientConnected(context);
        }

        /// <summary>
        /// 客户端发送数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        protected override void ChannelRead0(IChannelHandlerContext context, object msg)
        {
            _server.ClientMessage(context, msg);
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        /// <summary>
        /// 捕获异常
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
            _server.ClientException(context, exception);
        }

        /// <summary>
        /// 客户端关闭
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelInactive(IChannelHandlerContext context)
        {
            _server.ClientDisconnected(context);
        }

        /// <summary>
        /// 心跳检测
        /// </summary>
        /// <param name="context"></param>
        /// <param name="evt"></param>
        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent eventState)
            {
                if (eventState != null)
                {
                    context.Channel.CloseAsync();
                }
            }
        }

    }
}
